import { defineStore } from 'pinia'

export interface AdminInfo {
  username: string
  userId: number
  status: number
  role: number
  token?: string
}

function getDefaultAdmin(): AdminInfo | null {
  const raw = localStorage.getItem('adminInfo')
  if (raw) {
    try {
      return JSON.parse(raw)
    } catch {
      return null
    }
  }
  return null
}

export const useAdminStore = defineStore('admin', {
  state: () => ({
    adminInfo: getDefaultAdmin() as AdminInfo | null,
    expire: localStorage.getItem('adminExpire') ? Number(localStorage.getItem('adminExpire')) : 0
  }),
  actions: {
    setAdminInfo(info: AdminInfo, hours = 24) {
      this.adminInfo = info
      // 设置过期时间（默认24小时）
      const expire = Date.now() + hours * 60 * 60 * 1000
      this.expire = expire
      localStorage.setItem('adminInfo', JSON.stringify(info))
      localStorage.setItem('adminExpire', expire.toString())
    },
    clearAdminInfo() {
      this.adminInfo = null
      this.expire = 0
      localStorage.removeItem('adminInfo')
      localStorage.removeItem('adminExpire')
    },
    checkExpire() {
      if (this.expire && Date.now() > this.expire) {
        this.clearAdminInfo()
        return false
      }
      return true
    },
    
    // 检查是否为管理员角色
    isAdmin() {
      return this.adminInfo?.role === 1
    },
    
    // 检查是否已登录且为管理员
    isLoggedInAdmin() {
      return !!(this.adminInfo?.token && this.isAdmin() && this.checkExpire())
    }
  }
})
